﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
using WsValid;
using System.Web.BizCode;
using System.Data.Objects;
using WorkTimePrj.Models;

using System.Web;
using WorkTimePrj.Helper;
using System.Text;

namespace WorkTimePrj.Controllers
{
    public class SelectKeyPair
    {
        public string display { get; set; }
        public string label { get; set; }
        public Guid ID { get; set; }
        public string Number { get; set; }
    }

    public class ItemController : Controller
    {
        private WorkTimePrjEntities3 db = null;
        private WsFrameDataContext wsdb = null;
        public ItemController()
        {
            db = new WorkTimePrjEntities3();
            wsdb = new WsFrameDataContext();
        }
        // GET: /Item/
        [WSAuth(Roles = "2c05d336-4e01-420d-9081-14386430779b")]
        public ViewResult Index(DateTime? startTime = null, DateTime? endTime = null)
        {
            if (startTime == null || endTime == null || (endTime.Value - startTime.Value).Days >= 7)
            {
                int dayOfWeek = (int)DateTime.Today.DayOfWeek;
                if (dayOfWeek == 0)
                {
                    startTime = DateTime.Today.AddDays(-6);
                }
                else
                {
                    startTime = DateTime.Today.AddDays(-1 * dayOfWeek + 1);
                }
                endTime = startTime.Value.AddDays(+6);
            }
            ViewBag.startTime = startTime;
            ViewBag.endTime = endTime;
            List<SelectKeyPair> projectList = db.Project.OrderBy("it.status desc, it.display").Select(p => new SelectKeyPair
            {
                ID = p.pid,
                display = p.display,
                Number = p.code,
                label = "[" + p.status + "]" + p.display + "[" + p.code + "]"
            }).ToList();
            ViewBag.ProjectJson = new HtmlString(Newtonsoft.Json.JsonConvert.SerializeObject(projectList));

            string account = Consts.CurrentUser.Name;
            List<Item> list = db.Item.Where(e => e.account == account && (startTime <= e.starttime && endTime > e.starttime)).OrderByDescending(e => e.Project.status).ToList();
            if (list.Count < 10)
            {
                list.AddRange(new Item[10 - list.Count]);
            }

            Item[] items = list.ToArray();
            int WorkHours = 0;
            foreach (Item item in items)
            {
                if (item != null && item.cost != null)
                    WorkHours = WorkHours + item.cost.Value;
            }
            ViewBag.WorkHours = WorkHours;
            string rolenames = "";

            List<Guid> roles = wsdb.Relation.Where(l => l.ChildNodeID == Consts.CurrentUser.ID && l.Type == 1001).Select(s => s.ParentNodeID).ToList();
            foreach (Guid item in roles)
            {
                if (item == new Guid("db02cf61-1743-4248-b756-b4fde23af7fa"))
                    rolenames += "ART;";
                if (item == new Guid("9bcd6465-d530-4d0a-915c-eec1e7b765b1"))
                    rolenames += "DEV;";
                if (item == new Guid("60012941-1306-48b7-b829-f71934780c90"))
                    rolenames += "PM;";
                if (item == new Guid("bf55634d-851c-4a41-b10d-2aee7cd03d30"))
                    rolenames += "PRESALES;";
                if (item == new Guid("f0ac1a56-b8ef-404b-8ebb-07687671e141"))
                    rolenames += "TESTER;";
                if (item == new Guid("2ac26434-d4be-4b0b-9996-46c996fc6a8b"))
                    rolenames += "TS;";
                if (item == new Guid("BA144991-0307-4A52-B6E8-CA7B8FC3B5B9"))
                    rolenames += "ProjMgmt;";
            }
            ViewBag.roles = rolenames;
            return View(items);
        }

        [HttpPost]
        [WSAuth(Roles = "2c05d336-4e01-420d-9081-14386430779b")]
        public ActionResult Index(Item[] items, FormCollection form, DateTime? startTime = null, DateTime? endTime = null)
        {
            //PagedList<Item> item = db.Item.OrderBy(e => e.uid).ToPagedList(id ?? 1, 10);
            //return View(item);
            //var item = db.Item.Include("Project");
            if (form["HStartTime"] != "")
                startTime = DateTime.Parse(form["HStartTime"]);
            if (form["HEndTime"] != "")
                endTime = DateTime.Parse(form["HEndTime"]);
            if (startTime == null || endTime == null || (endTime.Value - startTime.Value).Days >= 7)
            {
                int dayOfWeek = (int)DateTime.Today.DayOfWeek;
                if (dayOfWeek == 0)
                {
                    startTime = DateTime.Today.AddDays(-6);
                }
                else
                {
                    startTime = DateTime.Today.AddDays(-1 * dayOfWeek + 1);
                }
                endTime = startTime.Value.AddDays(+6);
            }
            ViewBag.startTime = startTime;
            ViewBag.endTime = endTime;
            //ViewBag.pidSelectList = new SelectList(db.Project.OrderByDescending(e => e.status), "pid", "code_display_status");
            List<SelectKeyPair> proList = db.Project.Select(p => new SelectKeyPair
            {
                ID = p.pid,
                display = p.display,
                Number = p.code,
                label = "[" + p.status + "]" + p.display + "[" + p.code + "]"
            }).ToList();

            ViewBag.ProjectJson = Newtonsoft.Json.JsonConvert.SerializeObject(proList);
            string roles = "";
            List<Guid> rolearr = wsdb.Relation.Where(l => l.ChildNodeID == Consts.CurrentUser.ID && l.Type == 1001).Select(s => s.ParentNodeID).ToList();

            foreach (Guid item in rolearr)
            {
                if (item == new Guid("db02cf61-1743-4248-b756-b4fde23af7fa"))
                    roles += "ART;";
                if (item == new Guid("9bcd6465-d530-4d0a-915c-eec1e7b765b1"))
                    roles += "DEV;";
                if (item == new Guid("60012941-1306-48b7-b829-f71934780c90"))
                    roles += "PM;";
                if (item == new Guid("bf55634d-851c-4a41-b10d-2aee7cd03d30"))
                    roles += "PRESALES;";
                if (item == new Guid("f0ac1a56-b8ef-404b-8ebb-07687671e141"))
                    roles += "TESTER;";
                if (item == new Guid("2ac26434-d4be-4b0b-9996-46c996fc6a8b"))
                    roles += "TS;";
                if (item == new Guid("BA144991-0307-4A52-B6E8-CA7B8FC3B5B9"))
                    roles += "ProjMgmt;";
            }
            List<Project> projectList = db.Project.OrderBy("it.status desc, it.code").ToList();

            Wicresoft.Framework.Organization.User u = Consts.CurrentUser;
            string userName = u.Name;
            string userDspName = u.DisplayName;
            HttpBrowserCapabilitiesBase browerBase = ControllerContext.RequestContext.HttpContext.Request.Browser;
            string brower = browerBase.Browser + " " + browerBase.Version;

            for (int i = 0; i < 10; i++)
            {
                if (items[i].pid != null && items[i].cost != null)
                {
                    if (items[i].uid == Guid.Empty)
                    {
                        db.Item.AddObject(items[i]);
                        items[i].uid = Guid.NewGuid();
                        items[i].account = userName;
                        items[i].starttime = startTime;
                        items[i].submitter = userDspName;
                        items[i].submittime = DateTime.Now;
                        items[i].status = items[i].Project.status;
                        items[i].role = roles.Replace("ProjMgmt;", "").Trim(new char[] { ';' });
                        items[i].Brower = brower;
                    }
                    else
                    {
                        db.Item.Attach(items[i]);
                        ObjectStateEntry entry = db.ObjectStateManager.GetObjectStateEntry(items[i]);
                        entry.SetModifiedProperty("pid");
                        entry.SetModifiedProperty("cost");
                        entry.SetModifiedProperty("title");
                        items[i].submittime = DateTime.Now;
                        items[i].submitter = userDspName;
                        items[i].status = items[i].Project.status;
                        items[i].role = roles.Replace("ProjMgmt;", "").Trim(new char[] { ';' });
                        items[i].Brower = brower;
                        //this.ShowMessage("保存成功");
                        db.SaveChanges();
                    }
                }
                if (items[i] != null)
                    items[i].pidList = new SelectList(projectList, "pid", "code_display_status", items[i].pid);
            }
            this.ShowMessage("保存成功");
            db.SaveChanges();
            //string account = Consts.CurrentUser.Name;
            //items = db.Item.Where(e => e.account == account).OrderBy(e => e.uid).ToArray();
            return RedirectToAction("Index", "Item", new { startTime = ViewBag.startTime, endTime = ViewBag.endTime });
            //return View(items);
        }

        //
        // GET: /Item/Details/5
        [WSAuth(Roles = "2c05d336-4e01-420d-9081-14386430779b")]
        public ViewResult Details(Guid id)
        {
            Item item = db.Item.Single(i => i.uid == id);
            return View(item);
        }

        //
        // GET: /Item/Create
        [WSAuth(Roles = "2c05d336-4e01-420d-9081-14386430779b")]
        public ActionResult Create(int? refresh = null)
        {
            Item item = new Item();
            item.starttime = DateTime.Today.AddDays(-6-(int)DateTime.Today.DayOfWeek);
            SelectList sl = new SelectList(db.User.Where("it.State!=1").OrderBy(e => e.DisplayName), "Name", "DisplayName");
            ViewBag.uidSelectList = new SelectList(db.User.Where("it.State!=1").OrderBy(e => e.DisplayName), "Name", "DisplayName");
            
            List<SelectKeyPair> projectList = db.Project.OrderBy("it.status desc, it.display").Select(p => new SelectKeyPair
            {
                ID = p.pid,
                display = p.display,
                Number = p.code,
                label = "[" + p.status + "]" + p.display + "[" + p.code + "]"
            }).ToList();
            ViewBag.ProjectJson = new HtmlString(Newtonsoft.Json.JsonConvert.SerializeObject(projectList));

            
            if (refresh == null)
                ViewBag.refresh = 0;
            if (refresh == 1)
                ViewBag.refresh = 1;
            return View(item);
        }

        //
        // POST: /Item/Create

        [HttpPost]
        [WSAuth(Roles = "2c05d336-4e01-420d-9081-14386430779b")]
        public ActionResult Create(Item item)
        {
            List<WorkTimePrj.Models.User> userList = db.User.Where("it.State!=1").OrderBy(e => e.DisplayName).ToList();
            if (ModelState["account"].Errors.Count == 0 && ModelState["pid"].Errors.Count == 0 && ModelState["cost"].Errors.Count == 0 && ModelState["starttime"].Errors.Count == 0 && ModelState["title"].Errors.Count == 0)
            {
                db.Item.AddObject(item);
                item.uid = Guid.NewGuid();
                item.submittime = DateTime.Now;
                item.role = (item.role?? string.Empty).Replace("ProjMgmt;", "").Trim(new char[] { ';' });
                item.oper_user = Consts.CurrentUser.Name;
                item.oper_time = DateTime.Now;

                WorkTimePrj.Models.User u = userList.Single(l => l.Name == item.account);
                if (u != null)
                    item.submitter = u.DisplayName;
                HttpBrowserCapabilitiesBase browerBase = ControllerContext.RequestContext.HttpContext.Request.Browser;
                string brower = browerBase.Browser + " " + browerBase.Version;
                item.Brower = brower;
                db.SaveChanges();
                this.ShowMessage("保存成功");
                ViewBag.uidSelectList = new SelectList(db.User.Where("it.State!=1").OrderBy(e => e.DisplayName), "Name", "DisplayName");
                ViewBag.pidSelectList = new SelectList(db.Project.OrderBy("it.status desc, it.display"), "pid", "code_display_status");
                ViewBag.refresh = 1;
                return RedirectToAction("Create", new { refresh = 1 });
            }
            ViewBag.uidSelectList = new SelectList(userList, "Name", "DisplayName");
            //ViewBag.pidSelectList = new SelectList(db.Project.OrderBy("it.status desc, it.display"), "pid", "code_display_status");
            return View(item);
        }
        [HttpPost]
        [WSAuth(Roles = "2c05d336-4e01-420d-9081-14386430779b")]
        public ActionResult GetUserRole(string account)
        {

            string roles = "";
            List<Guid> rolearr = (from u in wsdb.Node
                                  join r in wsdb.Relation on u.ID equals r.ChildNodeID
                                  where r.Type == 1001 && u.Name == account
                                  select r.ParentNodeID).ToList();
            foreach (Guid item in rolearr)
            {
                if (item == new Guid("db02cf61-1743-4248-b756-b4fde23af7fa"))
                    roles += "ART;";
                if (item == new Guid("9bcd6465-d530-4d0a-915c-eec1e7b765b1"))
                    roles += "DEV;";
                if (item == new Guid("60012941-1306-48b7-b829-f71934780c90"))
                    roles += "PM;";
                if (item == new Guid("bf55634d-851c-4a41-b10d-2aee7cd03d30"))
                    roles += "PRESALES;";
                if (item == new Guid("f0ac1a56-b8ef-404b-8ebb-07687671e141"))
                    roles += "TESTER;";
                if (item == new Guid("2ac26434-d4be-4b0b-9996-46c996fc6a8b"))
                    roles += "TS;";
                if (item == new Guid("BA144991-0307-4A52-B6E8-CA7B8FC3B5B9"))
                    roles += "ProjMgmt;";
            }
            return Json(new { msg = roles });
        }
        [HttpPost]
        [WSAuth(Roles = "2c05d336-4e01-420d-9081-14386430779b")]
        public ActionResult GetStatus(string pid)
        {
            string status = string.Empty;

            Project project = db.Project.SingleOrDefault(i => i.pid == new Guid(pid));
            if (project != null)
                status = project.status;
            return Json(new { msg = status });
        }
        //
        // GET: /Item/Edit/5
        [WSAuth(Roles = "2c05d336-4e01-420d-9081-14386430779b")]
        public ActionResult Edit(Guid id)
        {
            Item item = db.Item.Single(i => i.uid == id);
            ViewBag.uidSelectList = new SelectList(db.User.Where("it.State!=1").OrderBy(e => e.DisplayName), "Name", "DisplayName");
            ViewBag.pidSelectList = new SelectList(db.Project.OrderBy("it.status desc, it.display"), "pid", "code_display_status");
            ViewBag.close = 0;
            return View(item);
        }

        //
        // POST: /Item/Edit/5

        [HttpPost]
        [WSAuth(Roles = "2c05d336-4e01-420d-9081-14386430779b")]
        public ActionResult Edit(Item item)
        {
            if (ModelState["account"].Errors.Count == 0 && ModelState["pid"].Errors.Count == 0 && ModelState["cost"].Errors.Count == 0 && ModelState["starttime"].Errors.Count == 0 && ModelState["title"].Errors.Count == 0)
            {
                db.Item.Attach(item);
                db.ObjectStateManager.ChangeObjectState(item, EntityState.Modified);
                item.oper_user = Consts.CurrentUser.Name;
                item.oper_time = DateTime.Now;
                db.SaveChanges();
                this.ShowMessage("保存成功");
                ViewBag.close = 1;
                ViewBag.uidSelectList = new SelectList(db.User.Where("it.State!=1").OrderBy(e => e.DisplayName), "Name", "DisplayName");
                ViewBag.pidSelectList = new SelectList(db.Project.OrderBy("it.status desc, it.display"), "pid", "code_display_status");
                return View(item);
            }
            ViewBag.uidSelectList = new SelectList(db.User.Where("it.State!=1").OrderBy(e => e.DisplayName), "Name", "DisplayName");
            ViewBag.pidSelectList = new SelectList(db.Project.OrderBy("it.status desc, it.display"), "pid", "code_display_status");
            return View(item);
        }

        [WSAuth(Roles = "2c05d336-4e01-420d-9081-14386430779b")]
        public ActionResult Delete(Guid uid, DateTime startTime, DateTime endTime)
        {
            Item item = db.Item.SingleOrDefault(i => i.uid == uid);
            if (item != null)
            {
                db.Item.DeleteObject(item);
                db.SaveChanges();
            }
            return RedirectToAction("Index", new { startTime = startTime, endTime = endTime });
        }

        [WSAuth(Roles = "2c05d336-4e01-420d-9081-14386430779b")]
        public ViewResult List(string orderBy, string account, string pid, int? id, DateTime? startTime = null, DateTime? endTime = null)
        {
            //startTime = new DateTime(2012, 2, 6);
            //DateTime endTime;
            if (startTime == null)
            {
                int dayOfWeek = (int)DateTime.Today.DayOfWeek;
                if (dayOfWeek == 0)
                {
                    startTime = DateTime.Today.AddDays(-6);
                }
                else
                {
                    startTime = DateTime.Today.AddDays(-1 * dayOfWeek + 1);
                }
            }
            if (endTime == null)
                endTime = startTime.Value.AddDays(+6);

            //account = Consts.CurrentUser.Name;
            IQueryable<vwItemProject> items = db.vwItemProject;
            if (account != "" && account != null)
                items = items.Where(i => i.account == account);
            if (pid != "" && pid != null)
                items = items.Where(i => i.pid == new Guid(pid));
            items = items.Where(i => i.starttime >= startTime);
            PagedList<vwItemProject> list;
            if (orderBy == "" || orderBy == null)
                list = items.OrderBy(e => e.User_DisplayName).ThenBy(e => e.Proj_Name).ThenBy(e => e.starttime).ToPagedList(id ?? 1, 10);
            else if (orderBy == "User_DisplayName asc")
                list = items.OrderBy(e => e.User_DisplayName).ThenBy(e => e.Proj_Name).ThenBy(e => e.starttime).ToPagedList(id ?? 1, 10);
            else if (orderBy == "User_DisplayName desc")
                list = items.OrderByDescending(e => e.User_DisplayName).ThenBy(e => e.Proj_Name).ThenBy(e => e.starttime).ToPagedList(id ?? 1, 10);
            else if (orderBy == "Proj_Name asc")
                list = items.OrderBy(e => e.Proj_Name).ThenBy(e => e.User_DisplayName).ThenBy(e => e.starttime).ToPagedList(id ?? 1, 10);
            else if (orderBy == "Proj_Name desc")
                list = items.OrderByDescending(e => e.Proj_Name).ThenBy(e => e.User_DisplayName).ThenBy(e => e.starttime).ToPagedList(id ?? 1, 10);
            else if (orderBy == "starttime asc")
                list = items.OrderBy(e => e.starttime).ThenBy(e => e.User_DisplayName).ThenBy(e => e.Proj_Name).ToPagedList(id ?? 1, 10);
            else if (orderBy == "starttime desc")
                list = items.OrderByDescending(e => e.starttime).ThenBy(e => e.User_DisplayName).ThenBy(e => e.Proj_Name).ToPagedList(id ?? 1, 10);
            else if (orderBy == "cost asc")
                list = items.OrderBy(e => e.cost).ThenBy(e => e.User_DisplayName).ThenBy(e => e.Proj_Name).ThenBy(e => e.starttime).ToPagedList(id ?? 1, 10);
            else if (orderBy == "cost desc")
                list = items.OrderByDescending(e => e.cost).ThenBy(e => e.User_DisplayName).ThenBy(e => e.Proj_Name).ThenBy(e => e.starttime).ToPagedList(id ?? 1, 10);
            else if (orderBy == "ack_type asc")
                list = items.OrderBy(e => e.ack_type).ThenBy(e => e.User_DisplayName).ThenBy(e => e.Proj_Name).ThenBy(e => e.starttime).ToPagedList(id ?? 1, 10);
            else if (orderBy == "ack_type desc")
                list = items.OrderByDescending(e => e.ack_type).ThenBy(e => e.User_DisplayName).ThenBy(e => e.Proj_Name).ThenBy(e => e.starttime).ToPagedList(id ?? 1, 10);
            else if (orderBy == "rate asc")
                list = items.OrderBy(e => e.rate).ThenBy(e => e.User_DisplayName).ThenBy(e => e.Proj_Name).ThenBy(e => e.starttime).ToPagedList(id ?? 1, 10);
            else if (orderBy == "rate desc")
                list = items.OrderByDescending(e => e.rate).ThenBy(e => e.User_DisplayName).ThenBy(e => e.Proj_Name).ThenBy(e => e.starttime).ToPagedList(id ?? 1, 10);
            else if (orderBy == "title asc")
                list = items.OrderBy(e => e.title).ThenBy(e => e.User_DisplayName).ThenBy(e => e.Proj_Name).ThenBy(e => e.starttime).ToPagedList(id ?? 1, 10);
            else
                list = items.OrderByDescending(e => e.title).ThenBy(e => e.User_DisplayName).ThenBy(e => e.Proj_Name).ThenBy(e => e.starttime).ToPagedList(id ?? 1, 10);
            ViewBag.startTime = startTime;
            ViewBag.endTime = endTime;
            ViewBag.orderBy = orderBy;
            ViewBag.account = account;
            ViewBag.pid = pid;
            ViewBag.uidSelectList = new SelectList(db.User.Where("it.State!=1").OrderBy(e => e.DisplayName), "Name", "DisplayName", account);
            ViewBag.pidSelectList = new SelectList(db.Project.OrderBy("it.status desc, it.display"), "pid", "code_display_status", pid);
            ViewBag.cnt = items.ToList().Count();
            return View(list);
        }

        [HttpPost]
        [WSAuth(Roles = "2c05d336-4e01-420d-9081-14386430779b")]
        public ActionResult List(FormCollection form, DateTime endTime, string orderBy)
        {
            string account = form["uidSelectList"];
            string pid = form["pidSelectList"];
            string startDate = form["TBStartTime"];
            DateTime startTime;
            //DateTime endTime;
            if (startDate != "")
            {
                startTime = DateTime.Parse(startDate);
                //endTime = startTime.AddDays(+6);
                //ViewBag.startTime = startTime;
                //ViewBag.endTime = endTime;
            }
            else
            {
                int dayOfWeek = (int)DateTime.Today.DayOfWeek;
                if (dayOfWeek == 0)
                {
                    startTime = DateTime.Today.AddDays(-6);
                }
                else
                {
                    startTime = DateTime.Today.AddDays(-1 * dayOfWeek + 1);
                }
                //endTime = startTime.AddDays(+6);
            }
            return RedirectToAction("List", new { orderBy = orderBy, account = account, pid = pid, id = 1, startTime = startTime, endTime = endTime });
        }


        [HttpPost]
        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        public ActionResult deleteitem(string ids)
        {
            string result = "0";
            try
            {
                string[] idArr = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                Guid[] gArr = new Guid[idArr.Length];
                for (int i = 0; i < idArr.Length; i++)
                {
                    gArr[i] = new Guid(idArr[i]);
                }


                List<Item> list = db.Item.Where(l => gArr.Contains(l.uid)).ToList();

                foreach (Item ob in list)
                {
                    db.Item.DeleteObject(ob);
                }

                db.SaveChanges();
            }
            catch
            {
                result = "1";
            }

            return Json(result);
        }

        public class UserRoleModel
        {
            public Guid UserID { get; set; }
            public string UserName { get; set; }
            public string Display { get; set; }
            public Guid? RoleID { get; set; }
            public string  RoleName { get; set; }
        }

        private class RoleModel
        {
            public string Display { get; set; }
            public Guid  RoleID { get; set; }
        }

        [HttpPost]
        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        public ActionResult Repair(string ps)
        {
            List<UserRoleModel> userList = new List<UserRoleModel>();

            string[] arr = ps.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);

            StringBuilder  sbsql = new StringBuilder();
            foreach (string item in arr)
            {
                UserRoleModel urm = new UserRoleModel();
                string [] pair = item.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                urm.UserName = pair[0];
                urm.RoleName = pair[1];
                userList.Add(urm);
                sbsql.AppendFormat(@"INSERT INTO  [Relation] ([ParentNodeID],[ChildNodeID],[SortIndex],[Type])
    SELECT '{0}',(SELECT ID FROM [Node] WHERE Name='{1}') AS ID ,0,1001
           WHERE NOT EXISTS ( SELECT ParentNodeID FROM  [Relation] v 
           WHERE v.ChildNodeID=(SELECT ID FROM [Node] WHERE Name='{1}') AND v.ParentNodeID ='{0}')", Const.Roles[urm.RoleName], urm.UserName);
            }

            List<string> userNames = userList.Select(l => l.UserName).ToList();

            List<string> newUserList = (from p in userNames
                        where  !db.User.Select(l=>l.Name).Contains(p)
                        select p).ToList();

            StringBuilder sb = new StringBuilder();

            List<Node> wsafUserList = ( from p in wsdb.Node 
                                        where userNames.Contains(p.Name) select p).ToList();
            foreach (Node item in wsafUserList)
            {
                string roleName = userList.SingleOrDefault(l => l.UserName == item.Name).RoleName;
                sb.AppendLine("select ID from [User] where Name='" + item.Name + "';");
                sb.AppendLine(" if @@rowcount =0 begin ");
                sb.AppendFormat(@" INSERT INTO [User]([ID],[Name],[DisplayName],[NodeType],[State],[Role]) VALUES  ( '{0}','{1}','{2}','User',0,'{3}');", item.ID, item.Name, item.DisplayName, roleName);
                sb.AppendLine(" end else begin  ");
                sb.AppendFormat(@" Update   [User]  set [Role] ='{0}' where Name='{1}';", roleName, item.Name);

                sb.AppendLine(" end  ");
            }

            //从框架里同步账号到worktimeprj
            if (sb.Length != 0)
            {

                db.ExecuteStoreCommand(sb.ToString());
            }

            // 初始化角色
            if (sbsql.Length != 0)
            {

                wsdb.ExecuteCommand(sbsql.ToString());
            }
            sb = new StringBuilder();
            sb.Append(@"UPDATE Item SET role = [user].Role2,submitter=[dbo].[User].DisplayName FROM [dbo].[User] WHERE [dbo].[User].Name= dbo.Item.account
AND [dbo].[User].Role2 IS NOT NULL");
            db.ExecuteStoreCommand(sb.ToString());


            return Json("1");
        }

        [WSAuth(Roles = "ba144991-0307-4a52-b6e8-ca7b8fc3b5b9")]
        public ActionResult DataRepair()
        {
            List<string> userItemList = db.Item.Select(l => l.account).Distinct().ToList();

            List<UserRoleModel> userList = (from u in wsdb.Node
                                            join r in
                                                (from ss in wsdb.Relation where Const.Roles.Values.Contains(ss.ParentNodeID)
                                                     && ss.ParentNodeID!= Const.Roles[Const.RoleName.ProjMgmt.ToString()] select ss)
                                             on u.ID equals r.ChildNodeID into bs
                                            from y in bs.DefaultIfEmpty()
                                            where userItemList.Contains(u.Name) && u.NodeType == "User"
                                            select new UserRoleModel { UserID = u.ID, UserName = u.Name, Display=u.DisplayName, RoleID = y.ParentNodeID }).OrderBy(o=>o.Display).ToList();
            List<RoleModel> roles = new List<RoleModel>();
            foreach (KeyValuePair<string, Guid> item in Const.Roles)
            {
                RoleModel rm = new RoleModel();
                rm.Display = item.Key;
                rm.RoleID = item.Value;
                roles.Add(rm);
            }
            ViewBag.Roles = new HtmlString(Newtonsoft.Json.JsonConvert.SerializeObject(roles));
            return View(userList);
        }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            wsdb.Dispose();
            base.Dispose(disposing);
        }
    }
}